package com.hd.trans.utils

import android.content.res.AssetManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Typeface
import com.bumptech.glide.Glide
import com.hd.trans.extension.ioExecute
import com.hd.trans.framework.rom.IOUtils
import com.hd.trans.ui.base.AppContextProvider
import com.hd.trans.utils.FileUtil.getCacheRoot
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.util.UUID

object BitmapUtilsKotlin {

    val ASSETS_CACHE_DIR: File by lazy {
        File(getCacheRoot(), "assets")
    }

    suspend fun getBitmapFromPath(path: String): Bitmap {
        return ioExecute() {
            val opts = BitmapFactory.Options()
            opts.inJustDecodeBounds = true
            BitmapFactory.decodeFile(path, opts)

            val mWidth = opts.outWidth
            val mHeight = opts.outHeight

            var targetW = mWidth
            var targetH = mHeight

            if (mWidth > mHeight) {
                if (mHeight > 720) {
                    targetH = 720
                    targetW = targetH * mWidth / mHeight
                }
            } else {
                if (mWidth > 720) {
                    targetW = 720
                    targetH = targetW * mHeight / mWidth
                }
            }
            Glide.with(AppContextProvider.getContext()).asBitmap().load(path).submit(targetW, targetH).get()
        }
    }

    /**
     * 旋转图片
     */
    suspend fun rotateBitmap(bitmap: Bitmap, degree: Int): Bitmap {
        if(degree==0){
            return bitmap
        }
        return ioExecute() {
            val matrix = Matrix()
            matrix.postRotate(degree.toFloat())
            Bitmap.createBitmap(
                bitmap,
                0,
                0,
                bitmap.width,
                bitmap.height,
                matrix,
                true
            )
        }
    }

    fun  deleteDir(dirPath: String?) {
        if (dirPath.isNullOrEmpty()) {
            return
        }
        val dir = File(dirPath)
        deleteDir(dir)
    }

    fun deleteDir(dir: File?) {
        if (dir == null || !dir.exists() || !dir.isDirectory)
            return
        val files = dir.listFiles() ?: return
        for (file in files) {
            if (file.isFile)
                file.delete() // 删除所有文件
            else if (file.isDirectory)
                deleteDir(file) // 递规的方式删除文件夹
        }
        dir.delete()// 删除目录本身
    }

    fun getTempDir():File{
        val dir = File(AppContextProvider.getContext().cacheDir,"temp")
        if (!dir.exists()) {
            dir.mkdirs()
        }
        return dir
    }

    /**
     * 获取国旗图片
     */
    /** 获取国旗图片缓存 */
    private val mNationalFlagImageCache = HashMap<String,Bitmap>()
    fun getNationalFlagBitmap(name: String): Bitmap {
        var bitmap = mNationalFlagImageCache[name]
        if (bitmap != null && !bitmap.isRecycled){
            return bitmap
        }
        val assetsFileName = "translate_language_icons_V4.zip"
        val dir = File(ASSETS_CACHE_DIR,assetsFileName)
        if (!dir.exists()){
            unZipAssets(assetsFileName,dir)
            //删除旧的文件夹
            deleteDir(dir.absolutePath.replace("4","3"))
        }
        val imageFile = File(dir,"${name}.webp")
        if (imageFile.exists()){
            bitmap = BitmapFactory.decodeFile(imageFile.absolutePath)
        }
        else {
            bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(bitmap)
            val paint = Paint()
            paint.color = Color.LTGRAY
            //绘制一个灰色的圆
            canvas.drawCircle(50f, 50f, 50f,paint)
            if (name.isNotEmpty()){
                paint.color = Color.BLACK
                paint.typeface = Typeface.MONOSPACE
                paint.textSize = 40f
                val fistChar = ""+name[0]
                val hWidth = paint.measureText(fistChar) / 2f
                val fm: Paint.FontMetrics = paint.fontMetrics
                val centerY = 50f - fm.descent + (fm.descent - fm.ascent) / 2f
                //绘制第一个字
                canvas.drawText(fistChar, 50f-hWidth, centerY, paint)
            }
        }

        mNationalFlagImageCache[name] = bitmap
        return bitmap
    }

    /**
     * 解压Assets文件到指定路径
     * @param name 文件名
     * @param dstDir 目的文件夹
     * @return 解压是否成功
     */
    fun unZipAssets(name: String, dstDir: File): Boolean {
        if (!dstDir.exists())
            dstDir.mkdirs()
        val tempFile = File(getTempDir(), UUID.randomUUID().toString())
        var success = copyAssets(name, tempFile)
        if (!success)
            return false
        try {
            ZipUtils.unzipFile(tempFile, dstDir)
        } catch (e: Exception) {
            success = false
        }
        tempFile.delete()
        return success
    }

    /**
     * 复制Assets文件到指定路径
     * @param name 文件名
     * @param dstFile 目的文件
     * @return 复制是否成功
     */
    fun copyAssets(name: String, dstFile: File): Boolean {
        var success = false
        val am: AssetManager = AppContextProvider.getContext().assets
        var inputStream: InputStream? = null
        var outStream: OutputStream? = null
        try {
            inputStream = am.open(name)
            val buffer = ByteArray(inputStream.available())
            inputStream.read(buffer)
            outStream = FileOutputStream(dstFile)
            outStream.write(buffer)
            success = true
        } catch (e:Exception) {
            e.printStackTrace()
        } finally {
            IOUtils.closeQuietly(inputStream)
            IOUtils.closeQuietly(outStream)
        }
        return success
    }
}